<!--查询或编辑表单-->
<template>
  <!-- inline  新增表单和回显表单 和 查询条件 写法不一样-->
  <el-form class="search-form public-events" :model="form" ref="form" :disabled="disabled" @submit.native.prevent :inline="!config.group">
    <!-- 新增表单和回显表单 -->
    <div v-if="config.group" class="form-group">
      <div v-for="(itemGroup, indexGroup) in config.props" :key="indexGroup">
        <div v-if="itemGroup.type === 'title'" class="little-title" :class="indexGroup == 0 ? 'firstChild' : ''" :span="24"><span></span>{{itemGroup.title}}</div>
        <el-row v-else class="form-group-row">
          <el-col v-for="(item, index) in getPorps(itemGroup.list)" :key="index" :span="item.span || 12" class="form-group-col">
            <el-form-item :label="item.label || ''" :prop="item.prop" :label-width="item.labelWidth || config.labelWidth || '70px'" :style="{width: item.width || '100%','min-width': item.minWidth || '226px',margin:item.margin}" :class="config.labelWidth ? 'el-form-item-' + config.labelWidth : 'el-form-item-84px'" :rules="[{ required: item.required || false, message: `${item.requiredTip}`, trigger: item.trigger || 'blur' }].concat(item.rules || [])">
              <el-select :size="item.size || 'small'" v-if="item.type === 'select'" filterable :clearable="!item.clearable" :style="{width: item.width || '100%'}" v-model="form[item.prop]" :placeholder="item.placeholder || '请选择'" :disabled="item.disabled" :multiple="item.multiple" @change="(value) => selectChange(value, item)">
                <el-option v-for="item in item.options" :key="item.value" :label="item.label || item.text" :value="item.value">
                </el-option>
              </el-select>
              <el-date-picker :size="item.size || 'small'" @change="onSearch" v-else-if="item.type === 'date'" v-model="form[item.prop]" :type="item.dateType || 'daterange'" range-separator="~" :start-placeholder="item.startPlaceholder || '开始日期'" :end-placeholder="item.endPlaceholder || '结束日期'" :value-format="item.format || 'yyyy-MM-dd'" :format="item.format || 'yyyy-MM-dd'" :style="{width: item.width || '100%'}" :disabled="item.disabled">
              </el-date-picker>
              <el-input :size="item.size || 'small'" v-else-if="item.type === 'input'" class="search-form-button-input" :type="item.inputType || 'text'" :rows="item.rows || 0" v-model="form[item.prop]" :placeholder="item.placeholder || '请输入'" clearable @blur="onChange" :disabled="item.disabled" :maxlength="item.maxlength" :show-word-limit="item.limit" :readonly="item.readonly">
                <template slot="prefix" v-if="item.prefixIcon">
                  <span :class="item.prefixIcon" :style="{color:item.prefixIconColor}"></span>
                </template>
                <template slot="suffix" v-if="item.suffixIcon">
                  <span :class="item.suffixIcon" :style="{color:item.suffixIconColor}"></span>
                </template>
                <template slot="append" v-if="item.append">{{item.append}}</template>
              </el-input>
              <el-input :size="item.size || 'small'" v-else-if="item.type === 'search'" class="search-form-button-input" :placeholder="item.placeholder || '请输入'" clearable v-model="form[item.prop]" @keyup.enter.native="onSearch">
                <el-button @click="onSearch" type="primary" icon="el-icon-search" slot="append">查询</el-button>
              </el-input>
              <el-upload v-else-if="item.type === 'upload'" :headers="item.headers" :action="item.uploadUrl" list-type="picture-card" :before-upload="(file) => {beforeAvatarUpload(file, item)}" :on-success="(response, file, fileList)=>{handleOnSuccess(response, file, fileList,item)}" :on-remove="(file, fileList)=>{handleOnRemove(file, fileList,item)}" :multiple="true" :accept="item.accept">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-cascader :size="item.size || 'small'" v-else-if="item.type === 'selectTree'" :collapse-tags="true" v-model="form[item.prop]" :options="item.options" :props="item.props" :disabled="item.disabled" @change="selectTreeChange"></el-cascader>
              <div class="detail-container" :class="[{'text-overflow':item.overflow || false}]" :style="{width: item.width || '100%',}" v-else-if="item.type === 'detail'">
                {{item.formatter ? item.formatter(form, item) : form[item.prop]}}
              </div>
              <div v-else-if="item.type === 'radio'">
                <el-radio-group v-model="form[item.prop]" @input="()=>item.change()">
                  <el-radio :label="v.value" v-for="(v,i) in item.options" :key="i">{{v.label}}</el-radio>
                </el-radio-group>
              </div>
              <div v-else-if="item.type === 'slot'">
                <slot :name="item.slotName"></slot>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-form-item v-if="showButton && type === 'search'" class="form-item-button">
        <el-button type="primary" @click.stop="onAllSearch">查询</el-button>
        <slot name="custom-button"></slot>
      </el-form-item>
    </div>
    <div v-else class="form-list" :class="collapse">
      <!-- 查询条件 -->
      <el-form-item v-for="(item, index) in getPorps" :key="index" :label="item.label || ''" :prop="item.prop" class="inline-form-item" :label-width="item.labelWidth || config.labelWidth || '70px'" :style="{'padding-left': item.paddingLeft || '0', 'padding-right': item.paddingRight || '16px', 'min-width': item.minWidth,margin:item.margin}" :rules="[{ required: item.required || false, message: `${item.requiredTip}`, trigger: item.trigger || 'blur' }]">
        <!-- {{item}} -->
        <el-select :size="item.size || 'small'" v-if="item.type === 'select'" filterable :clearable="!item.clearable" :style="{width: item.width || '100%'}" v-model="form[item.prop]" :placeholder="item.placeholder || '请选择'" :disabled="item.disabled" :multiple="item.multiple" @change="(value) => selectChange(value, item)">
          <el-option v-for="item in item.options" :key="item.id || item.value" :label="item.label || item.text" :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker :size="item.size || 'small'" @change="onSearch" v-else-if="item.type === 'date'" v-model="form[item.prop]" :type="item.dateType || 'daterange'" range-separator="~" :start-placeholder="item.startPlaceholder || '开始日期'" :end-placeholder="item.endPlaceholder || '结束日期'" :value-format="item.format || 'yyyy-MM-dd'" :format="item.format || 'yyyy-MM-dd'" :style="{width: item.width || '100%'}" :disabled="item.disabled">
        </el-date-picker>
        <el-input :size="item.size || 'small'" v-else-if="item.type === 'input'" class="search-form-button-input" :style="{width: item.width || '100%'}" :type="item.inputType || 'text'" :rows="item.rows || 0" v-model="form[item.prop]" :placeholder="item.placeholder || '请输入'" clearable @blur="onChange" :disabled="item.disabled"></el-input>
        <el-input :size="item.size || 'small'" v-else-if="item.type === 'search'" class="search-form-button-input" :style="{width: item.width || '100%'}" :placeholder="item.placeholder || '请输入'" clearable v-model="form[item.prop]" @keyup.enter.native="onSearch">
          <el-button @click="onSearch" type="primary" icon="el-icon-search" slot="append"></el-button>
        </el-input>
        <el-cascader :size="item.size || 'small'" v-else-if="item.type === 'selectTree'" :collapse-tags="true" :style="{width: item.width || '100%'}" v-model="form[item.prop]" :options="item.options" :props="item.props" :disabled="item.disabled" clearable @change="selectTreeChange"></el-cascader>
        <div v-else-if="item.type === 'title'" class="little-title"><span></span>{{item.title}}</div>
        <div v-else-if="item.type === 'slot'">
          <slot :name="item.slotName"></slot>
        </div>
      </el-form-item>
      <!-- 查询按钮 默认margin使用第一条配置项的距离-->
      <el-form-item v-if="showButton && type === 'search'" class="form-item-button">
        <el-button type="primary" @click.stop="onAllSearch" size="small" :loading="loading">查询</el-button>
        <el-button v-if="showReset" @click.stop="resetForm" size="small">重置</el-button>
        <!--        <span v-if="getPorps.length > 6" class="open-close-tip" @click="openClose">-->
        <!--          {{collapseLabel}}-->
        <!--          <i :class="collapseIcon"></i>-->
        <!--        </span>-->
        <slot name="custom-button"></slot>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
import {
  Form as elForm,
  FormItem as elFormItem,
  Input as elInput,
  Select as elSelect,
  Button as elButton,
  Row as elRow,
  Col as elCol,
  Option as elOption,
  DatePicker as elDatePicker,
  Upload as elUpload,
  Cascader as elCascader,
  RadioGroup as elRadioGroup,
  Radio as elRadio,
} from "element-ui"
export default {
  name:'VtForm',
  props: {
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    form: {
      type: Object,
      default: () => {
        return {}
      }
    },
    inline: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    showButton: {
      type: Boolean,
      default: true
    },
    type: {
      type: String,
      default: 'search'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isUploadFile: {
      type: Boolean,
      default: false
    },
    clearList: {
      type: Boolean,
      default: false
    },
    showReset: {
      type: Boolean,
      default: false
    },
    loading:{
      type: Boolean,
      default: false
    },
  },
  components:{
    elForm,
    elFormItem,
    elInput,
    elSelect,
    elButton,
    elRow,
    elCol,
    elOption,
    elDatePicker,
    elUpload,
    elCascader,
    elRadioGroup,
    elRadio,
  },
  computed: {
    getPorps () {
      return this.config.group ?
          function (list) {
            // console.log(list)
            return list.filter((item) => !item.hide)
          } :
          this.config.props.filter((item) => !item.hide)
    }
  },
  watch: {
    isUploadFile (val) {
      if (val) {
        this.uploadFile()
      }
    },
    clearList (val) {
      if (val) {
        this.fileList = []
      }
    }
  },
  data () {
    return {
      fileList: [],
      uploadUrl: '',
      collapse: 'close',
      collapseLabel: '展开',
      collapseIcon: 'el-icon-angle-down', // 展开，收起图片
      fileData: {} // formData
    }
  },
  created () {},
  mounted () {},
  methods: {
    openClose () {
      if (this.collapse === 'close') {
        this.collapse = 'open'
        this.collapseLabel = '收起'
        this.collapseIcon = 'el-icon-angle-up'
      } else {
        this.collapse = 'close'
        this.collapseLabel = '展开'
        this.collapseIcon = 'el-icon-angle-down'
      }
    },
    onAllSearch () {
      this.$emit('update:loading',true)
      this.$emit('search')
    },
    onSearch () {
      if (!this.showButton && this.type === 'search') {
        this.$emit('search')
      }
    },
    onChange () {
      this.$emit('search')
    },
    resetForm () {
      this.$emit('reset')
    },
    selectChange (value, item) {
      if (item.callback) {
        item.callback(value)
      }
      if (!this.showButton && this.type === 'search') {
        this.$emit('search')
      }
    },
    /**
     * 下载上传的文件
     **/
    async handleDownload (file) {},
    /**
     * 删除上传到数据库的文件
     **/
    handleOnRemove (file, fileList, item) {
      this.form[item.prop] = fileList.map((v) =>
          item.resultFunction(v.response)
      )
    },
    /**
     * 删除临时上传的文件
     **/
    deleteFileList (index, item) {},
    beforeAvatarUpload (file, item) {
      console.log(file, item)
      const fileName = file.name
      // 上传的类型
      const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      const uploadType = item.uploadType
      // 可以限制上传文件的格式
      if (uploadType && !uploadType.includes(fileType)) {
        this.$message.error(`文件格式错误,支持格式${uploadType.join('、')}`)
        return false
      }
      // 可以限制文件大小
      if (size > item.size) {
        this.$message.error(`文件不能超过${item.size}MB`)
        return false
      }
      this.$emit('beforeUpload')
      this.fileList.push(file)
      return true
    },
    // 上传成功,将上传的数据插入到数组中
    handleOnSuccess (response, file, fileList, item) {
      let url = item.resultFunction(response)
      Array.isArray(this.form[item.prop]) ?
          this.form[item.prop].push(url) :
          (this.form[item.prop] = [url])
    },
    async uploadFile () {},
    selectTreeChange () {},
    clearFormValidator () {
      this.$refs.form.clearValidate()
    },
    formValidator () {
      return this.$refs.form.validate()
    },
    formResetFields(){
      return this.$refs.form.resetFields()
    }
  }
}
</script>

